package visualizer.google;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class GoogleRequestUrlBuilder {
	private static final String ENCODING = "UTF-8";
	private static final String BASE = "http://ajax.googleapis.com/ajax/services/{service}/{category}?v=1.0";
	private String service = "search";
	private String category = "web";
	private Map<String, String> params = new HashMap<String, String>();
	
	public GoogleRequestUrlBuilder set(String key, String value)
	{
		params.put(key, value);
		return this;
	}
	
	public boolean has(String key)
	{
		return params.containsKey(key);
	}
	
	public String get(String key)
	{
		return params.get(key);
	}
	
	public GoogleRequestUrlBuilder setService(String service)
	{
		this.service = service;
		return this;
	}
	
	public GoogleRequestUrlBuilder setCategory(String category)
	{
		this.category = category;
		return this;
	}
	
	public GoogleRequestUrlBuilder setQuery(String query)
	{
		return set("q", query);
	}
	
	public URL build()
	{
		String base = getBaseUrl();
		String query = getQuery();
		
		try {
			return new URL(base + query);
		} catch (MalformedURLException e) {
			return null;
		}
	}
	
	public String getBaseUrl()
	{
		String base = "" + this.BASE;
		base = base.replace("{service}", service);
		base = base.replace("{category}", category);
		return base;
	}
	
	public String getQuery()
	{
		String result = "";
		for (Map.Entry<String, String> e : params.entrySet()) {
			result += "&" + encode(e.getKey()) + "=" + encode(e.getValue());
		}
		return result;
	}
	
	public String encode(String s)
	{
		try {
			return URLEncoder.encode(s, ENCODING);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Your system does not support " + ENCODING + " encoding");
		}
	}
}
